<template>
  <div class="container">
    <el-form
      ref="loginForm"
      :model="formData"
      :rules="rules"
      label-width="auto"
      hide-required-asterisk
    >
      <h1>十方智育 - 后台登录</h1>
      <el-form-item label="用户名" prop="username">
        <el-input
          size="large"
          v-model="formData.username"
          placeholder="请输入账号"
          :prefix-icon="Avatar"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          size="large"
          v-model="formData.password"
          placeholder="请输入密码"
          type="password"
          show-password
          :prefix-icon="Lock"
        >
        </el-input>
      </el-form-item>
      <el-form-item style="margin-left: 54px">
        <el-button type="primary" @click="login(loginForm)">登录</el-button>
        <el-button @click="resetForm(loginForm)">取消</el-button>
        <el-button type="success" @click="registerDialogVisible = true">注册</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="注册" v-model="registerDialogVisible" width="500px">
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userpwd">
          <el-input v-model="registerForm.userpwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="registerForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="registerForm.nickname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRegister">提交</el-button>
          <el-button @click="registerDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/stores/counter'
import { getCurrentInstance, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Avatar, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const counter = useUserStore()
const loginForm = ref<FormInstance>()
const formData = reactive({
  username: '',
  password: '',
})
const rules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '长度至少 6 个字符', trigger: 'blur' },
  ],
})
const axios = getCurrentInstance().appContext.config.globalProperties.axios
const router = useRouter()
const login = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(formData.username, formData.password)
      axios.post(`auth/login`,null,
          {params: {
            username: formData.username,
            userpwd: formData.password
         }})
        .then((resp) => {
          console.log(resp.data)
          if (resp.code == 200) {
            //存到sessionStorage里
            ElMessage.success('登陆成功')
            counter.setUserInfo(resp.data)
            // console.log(counter.userInfo);
            router.replace('/index')
          } else {
            ElMessage.error('账号或密码错误')
          }
        })
    } else {
      ElMessage.error('请输入正确的账号和密码')
    }
  })
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
const registerDialogVisible = ref(false)
const registerFormRef = ref()
const registerForm = reactive({
  username: '',
  userpwd: '',
  mobile: '',
  email: '',
  nickname: '',
  salt: '',
  del: 0,
})
const registerRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userpwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
})
const submitRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerForm.salt = Math.random().toString(36).slice(2, 10)
      registerForm.del = 0
      try {
        const resp = await axios.post(
          'auth/register',
          { ...registerForm },
          { headers: { 'Content-Type': 'application/json' } },
        )
        if (resp.code === 200) {
          ElMessage.success('注册成功，请登录')
          registerDialogVisible.value = false
        } else {
          console.log(resp)
          ElMessage.error(resp.data?.msg || '注册失败')
        }
      } catch (e) {
        ElMessage.error('注册请求失败')
      }
    }
  })
}
</script>

<style scoped>
.container {
  height: 100vh;
  background: url('../assets/login_bg.jpg') no-repeat;
  background-size: 100%;
  overflow: hidden;
  position: relative;
}

.el-form {
  width: 500px;
  /* margin: 150px auto; */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 30px 50px;
  border-radius: 10px;
  box-shadow:
    0 8px 16px rgba(0, 0, 0, 0.12),
    0 0 6px rgba(0, 0, 0, 0.04);
  background: rgba(255, 255, 255, 0.8);
}

h1 {
  text-align: center;
}
</style>
